package com.zhimeng.personal.data;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.amap.api.maps.model.LatLng;
import com.zhimeng.personal.models.User;
import com.zhimeng.personal.utils.JSONUtils;

/**
 * Created by sunzhimeng on 10/31/17.
 */

public class DataCenter {
    private static boolean signedIn = false;
    private static Context mContext;
    private static LatLng mlng;
    private static String currentAddress;
    private static User user = visiter();

    public static User getCurrentUser() {
        return user;
    }

    public static void register(Context context) {
        mContext = context;
        user =  JSONUtils.getUserFromJson(context);
    }

    public static int getCurrentUserId() {
        if (getCurrentUser() == null) return -1;
        return getCurrentUser().getId();
    }

    public static boolean isSigned() {
        return signedIn;
    }

    public static String getCurrentToken() {
        return user.getAccessToken();
    }

    public static boolean setSignedIn(User u) {
        user = u;
         JSONUtils.saveUserToJson(user, mContext);
//        DBUtils.connectDB(mContext);
//        DBUtils.saveUser(user);
        signedIn = !TextUtils.isEmpty(getCurrentToken());
        Log.i("*********** isSigned", (signedIn ? "with token " + getCurrentToken() : " *********"));
        return signedIn;
    }

    public static void simpleLogin(User u) {
        user = u;
         JSONUtils.saveUserToJson(user, mContext);
    }

    public static String getCurrentAddress() {
        return currentAddress;
    }

    public static void setCurrentAddress(String currentAddress) {
        DataCenter.currentAddress = currentAddress;
    }

    public static void setCurrentLocation(LatLng lng) {
        mlng = lng;
    }

    public static LatLng getCurrentLocation() {
        return mlng;
    }

    public static String getCurrentLocationString() {
        return mlng == null ? "" : mlng.longitude + "," + mlng.latitude;
    }

    public static String getLastMobile() {
        return  JSONUtils.getUserFromJson(mContext).getPhone();
    }

    public static boolean login() {
        login(user);
        return isSigned();
    }

    public static void login(User user) {
        if (user == null || user.getId() <= 0) return;
        setSignedIn(user);
    }

    public static void logout() {
        user = visiter();
         JSONUtils.saveUserToJson(user, mContext);
        signedIn = false;
    }

    public static User visiter() {
        User u = new User();
        u.setAccessToken("");
        if (user != null) u.setPhone(user.getPhone());
        u.setId(-1);
        return u;
    }

}
